package com.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import java.util.List;
import java.io.StringReader;




public class HttpUtil {
    public static boolean isRunning(String ip) throws Exception {
        boolean isRun=false;
        try{
             URL url=new URL("http://"+ip);
             URLConnection conn=url.openConnection();
             conn.connect();
             isRun=true;
        }catch(Exception ex){
            if(ex instanceof MalformedURLException){
                throw ex;
            }
        }
        return isRun;
    }
    
    public static String request(String urlStr,String postData){
    	String reString = "";
		try {

			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			//这里是关键，表示我们要向链接里输出内容
			conn.setDoOutput(true);
			//获得连接输出流　
			OutputStreamWriter out= new OutputStreamWriter(conn.getOutputStream());

			out.write(postData);
			out.flush();
			out.close();

			//到这里已经完成了，不过我们还是看看返回信息吧
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;

			//int lineNum = 1 ;
			while( ( line=reader.readLine() ) != null ) {

			//	System.out.println(line);
				reString += line;
			}
		} catch (Exception e) {

			e.printStackTrace();
			return "error:" + e.getMessage();
		}
		return reString;
    }
    
    public static String[] parseSimpleXmlData(String xmlStr,String[] keys){
		
    	String[] res = new String[keys.length];

		try{

			StringReader read = new StringReader(xmlStr);//创建一个新的字符串
			InputSource source = new InputSource(read); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			SAXBuilder sb = new SAXBuilder(); //创建一个新的SAXBuilder
			Document doc = sb.build(source);//通过输入源构造一个Document

			Element rootElement = doc.getRootElement(); //取的根元素
			Element et = null;

			List<Element> list=rootElement.getChildren();

			for(Element e:list){
				for(int i = 0 ; i < keys.length ; i++ ){
					if( e.getName().equals(keys[i]) ){
						res[i] = e.getValue();
					}
				}
			}
		}
		catch(Exception e){
			return res;
		}
		return res;
	}
    
    public static void main(String[] args) throws Exception {
        System.out.println(isRunning("127.0.0.1:8081"));
    }
}
